package com.hsy.crm.web.service.base;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hsy.crm.web.domain.entity.*;
import com.hsy.crm.web.domain.ex.ServiceException;
import com.hsy.crm.web.mapper.*;
import com.hsy.crm.web.utils.DateUtils;
import com.hsy.crm.web.utils.DictUtils;
import com.hsy.crm.web.utils.ListUtils;
import com.hsy.crm.web.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Table;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by admin on 2018/8/17.
 */
@Service
public class DataInitService {

    @Autowired
    DictMapper dictMapper;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    SchemaMapper schemaMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    VendorMapper vendorMapper;

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    StoreProductDetailMapper storeProductDetailMapper;

    private static AtomicLong CODE_INDEX;
    private static AtomicLong STORE_DETAIL_INDEX = new AtomicLong(1);

    private static String NOW_DATE_SHORT_FORMAT = DateUtils.formatShort(DateUtils.now());

    /**
     * 初始化字典
     */
    public void initDict(){
        DictUtils.setDicts(dictMapper.selectAllDict());
    }

    public void initProductIds(List<PlatformCustomer> customers){
        for (PlatformCustomer platformCustomer : customers){
            List<Long> productIds = productMapper.getProductIds(platformCustomer.getPlatCustomerId());
            CacheService.putProductIds(platformCustomer.getPlatCustomerId(),productIds);
        }
    }

    public void initVendorIds(List<PlatformCustomer> customers){
        for (PlatformCustomer platformCustomer : customers){
            List<Long> vendorIds = vendorMapper.getVendorIds(platformCustomer.getPlatCustomerId());
            CacheService.putVendorIds(platformCustomer.getPlatCustomerId(),vendorIds);
        }
    }

    public void initCustomerIds(List<PlatformCustomer> customers){
        for (PlatformCustomer platformCustomer : customers){
            List<Long> customerIds = customerMapper.getCustomerIds(platformCustomer.getPlatCustomerId());
            CacheService.putCustomerIds(platformCustomer.getPlatCustomerId(),customerIds);
        }
    }


    public void initMenus(){

        List<Menu> menus = menuMapper.selectAll();
        Map<Long,Menu> map = Maps.newHashMap();
        for( Menu menu : menus ){
            map.put(menu.getId(),menu);
        }
        CacheService.putMenus(map);
    }

    public void initStoreProductDetailIndex(List<PlatformCustomer> customers){
        List<Long> maxSorts = Lists.newArrayList();
        for( PlatformCustomer platCustomer : customers ){
            maxSorts.add(storeProductDetailMapper.selectMaxSort(platCustomer.getPlatCustomerId()));
        }
        Collections.sort(maxSorts);
        long maxSort = 1;
        if( ListUtils.isNotEmpty(maxSorts) ){
            maxSort = maxSorts.get(maxSorts.size()-1).longValue();
        }
        DataInitService.STORE_DETAIL_INDEX = new AtomicLong(maxSort);
    }


    /**
     * 初始化订单编号
     * 所有订单共用同一个编号
     * 所有客户累计每天可以使用最多   1000w   个编号
     */
    public void initCodeIndex(List<PlatformCustomer> customers) {

        DataInitService.NOW_DATE_SHORT_FORMAT = DateUtils.formatShort(DateUtils.now());
        List<Long> maxCodes = Lists.newArrayList();

        Class<?>[] orderClasses = {Order.class,TransferOrder.class,SplitProduct.class,
                StoreCheck.class,StoneOther.class,ReceiptOrder.class,FinOtherOrder.class,FinTransOrder.class,VerificateOrder.class};

        for( PlatformCustomer platCustomer : customers ){
            for( Class<?> clazz : orderClasses ){
                maxCodes.add(this.getMaxCode(clazz,platCustomer.getPlatCustomerId()));
            }
        }

        Collections.sort(maxCodes);

        long maxCode = 1;
        if( ListUtils.isNotEmpty(maxCodes) ){
            maxCode = maxCodes.get(maxCodes.size()-1).longValue();
        }

        DataInitService.CODE_INDEX = new AtomicLong(maxCode);
    }

    public static Long getSort(){
        return STORE_DETAIL_INDEX.incrementAndGet();
    }

    public static String getOrderCode() {
        //到第二天时自动变成1
        String nowDateShortFormat = DateUtils.formatShort(DateUtils.now());
        if (!nowDateShortFormat.equals(DataInitService.NOW_DATE_SHORT_FORMAT)) {
            synchronized (DataInitService.class){
                if (!nowDateShortFormat.equals(DataInitService.NOW_DATE_SHORT_FORMAT)) {
                    DataInitService.CODE_INDEX = new AtomicLong(1);
                    DataInitService.NOW_DATE_SHORT_FORMAT = nowDateShortFormat;
                }
            }
        }

        long index = DataInitService.CODE_INDEX.incrementAndGet();
        if (index > 9999999) {
            throw new ServiceException("no code index to use");
        }

        String code = nowDateShortFormat + String.format("%07d", index);
        return code;
    }

    /**
     * 获取最大编号
     */
    private Long getMaxCode(Class<?> clazz,String customerId){

        Table table = clazz.getAnnotation(Table.class);
        String tableName = table.name() + "_" + customerId;

        String sql = "select code from "+tableName+" order by code desc limit 1";
        String code = schemaMapper.executeQuery(sql);
        if(StringUtils.isEmpty(code)){
            return 0L;
        }else{
            return Long.parseLong(code.substring(8));
        }


    }



}
